from django import forms
from django.shortcuts import render, redirect
from django.contrib import messages
from utils.pager import Pagination

from www.models import Customer, Level
from django.db.models import Q


def customer_list(request):
    # 后端使用消息如下
    message = messages.get_messages(request)
    for msg_obj in message:
        print('发送消息', msg_obj, type(msg_obj))
    keyword = request.GET.get('keyword', "").strip()
    con = Q()
    if keyword:
        con.connector = 'OR'
        con.children.append(('username__contains', keyword))
        con.children.append(('mobile__contains', keyword))
        con.children.append(('level__title__contains', keyword))
    queryset = Customer.objects.filter(active=1).filter(con).order_by('-id')
    pager = Pagination(request, queryset)
    return render(request, 'customer.html', {"pager": pager, 'keyword': keyword})


from utils.bootstrap import BootStrapForm

from utils.encrypt import md5_string


class CustomerModelForm(BootStrapForm, forms.ModelForm):
    exclude_field_list = ['level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['level'].queryset = Level.objects.filter(active=1)

    password = forms.CharField(widget=forms.PasswordInput(render_value=True), label='密码')
    password_repeat = forms.CharField(widget=forms.PasswordInput(render_value=True), label='确认密码')

    class Meta:
        model = Customer
        fields = ['level', 'username', 'mobile', 'password', 'password_repeat']
        widgets = {
            'level': forms.RadioSelect(attrs={'class': 'form-radio'}),  # 设置 level 字段的默认组件类型,
        }

    def clean_password(self):
        password = self.cleaned_data['password']
        md5_pwd = md5_string(password)
        return md5_pwd

    def clean_password_repeat(self):
        password = self.cleaned_data['password']
        password_repeat = md5_string(self.cleaned_data['password_repeat'])
        if password != password_repeat:
            raise forms.ValidationError('密码不一致')
        md5_pwd_repeat = md5_string(password_repeat)
        return md5_pwd_repeat


def customer_add(request):
    origin = request.GET.get('redirect', '/home/')
    if request.method == "GET":
        form = CustomerModelForm()
        return render(request, 'form.html', {'form': form})

    form = CustomerModelForm(request.POST or None)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    administrator_id = request.nb_user.id
    form.instance.creator_id = administrator_id
    form.save()
    # 用户添加数据成功后保存一段数据到message
    messages.add_message(request, messages.SUCCESS, "添加成功")
    return redirect(origin)


class CustomerEditModelForm(BootStrapForm, forms.ModelForm):
    exclude_field_list = ['level']

    class Meta:
        model = Customer
        fields = ['level', 'username', 'mobile']
        widgets = {
            'level': forms.RadioSelect(attrs={'class': 'form-radio'})
        }


def customer_edit(request, pk):
    origin = request.GET.get('redirect', '/home/')
    instance = Customer.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = CustomerEditModelForm(instance=instance)
        return render(request, 'form.html', {'form': form})
    form = CustomerEditModelForm(instance=instance, data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(origin)


def customer_delete(request, pk):
    origin = request.GET.get('redirect', '/home/')
    if request.method == 'GET':
        return render(request, 'delete.html', {'origin': origin})
    instance = Customer.objects.filter(id=pk).update(active=0)
    return redirect(origin)


class CustomerResetModelForm(BootStrapForm, forms.ModelForm):
    password_repeat = forms.CharField(widget=forms.PasswordInput(render_value=True), label='确认密码', required=False)
    password = forms.CharField(widget=forms.PasswordInput(render_value=True), label='密码', required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 隐藏密码和确认密码字段
        self.initial['password'] = ''

    def clean_password(self):
        password = md5_string(self.cleaned_data['password'])
        return password

    def clean_password_repeat(self):
        password_repeat = md5_string(self.cleaned_data['password_repeat'])
        password = self.cleaned_data['password']
        if password != password_repeat:
            raise forms.ValidationError('两次密码不一致')
        return password_repeat

    class Meta:
        model = Customer
        fields = ['username', 'password', 'password_repeat']
        widgets = {
            'username': forms.TextInput(attrs={'readonly': True})  # 设置用户名为只读
        }


def customer_reset(request, pk):
    origin = request.GET.get('redirect', '/home/')
    instance = Customer.objects.filter(id=pk).first()
    # initial_data = {'username': instance.username}
    if request.method == 'GET':
        form = CustomerResetModelForm(instance=instance)
        return render(request, 'form.html', {"form": form})
    form = CustomerResetModelForm(data=request.POST, instance=instance)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(origin)
